package br.adm.martins.prp.presentation.web;

import java.util.List;

import javax.inject.Inject;

import br.adm.martins.prp.business.entity.BaseEntity;
import br.adm.martins.prp.business.control.CrudService;
import org.primefaces.event.RowEditEvent;
import org.slf4j.Logger;




@SuppressWarnings("unchecked")
public class CrudMB<T extends BaseEntity> {
	
	@Inject
	private CrudService service;
        
        @Inject 
        private Logger log;
 	
	private T entity;
	private List<T> entityList;
	private T[] selecteds;

	
	public CrudMB(Object obj) {
		this.entity = (T) obj;
	}
	
	public CrudMB(){
	}	
	
	public void create() {
		service.create(entity);
		
//		entity = (E) new Object();
		
		entityList = service.findAll(entity);
	}

	public void update() {
            log.info("Method: Update entity..");
		service.update(entity);
	}

	public void remove() {
		service.delete(entity);
	}



	public void removeSelecteds() {
            
            log.info("Method: Remove Selecteds.. ");
            
		for (T t : selecteds){
			service.delete(t);
		}
		selecteds = null;
		entityList = service.findAll(entity);
	}

	public void onEditRow(RowEditEvent event) {

		this.entity = (T) event.getObject();

		this.update();

	}
	
	public T getEntity() {
		return entity;
	}

	public void setEntity(T entity) {
		this.entity = entity;
	}


	public T[] getSelecteds() {
		return selecteds;
	}

	public void setSelecteds(T[] selecteds) {
		this.selecteds = selecteds;
	}

	public List<T> getEntityList() {
		
		if(entityList == null) 
			entityList = service.findAll(entity);
		
		return entityList;
	}
	
}
